package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.heima.model.common.constants.wemedia.WemediaConstants.CANCEL_COLLECT_MATERIAL;
import static com.heima.model.common.constants.wemedia.WemediaConstants.COLLECT_MATERIAL;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    private String prefix;
    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 上传照片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1.校验参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文件不存在");
        }
        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //获取原文件路径
        String originalFilename = multipartFile.getOriginalFilename();
        Boolean result = checkFileSuffix(originalFilename);
        if (!result) {
            CustException.cust(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        // 2 上传到oss
        String fileId = null;
        try {
            String filename = UUID.randomUUID().toString().replaceAll("-", "");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId = fileStorageService.store(prefix, filename + suffix, multipartFile.getInputStream());
            log.info("阿里云OSS 文件 fileId: {}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云OSS 文件上传失败,原因: {}", e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "服务器繁忙请稍后重试");
        }
        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        // 设置文件id
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(fileId);
        this.save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite + fileId);
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        // 1.参数校验
        dto.checkParam();
        // 2 执行业务查询
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        // 收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 当前登录用户的素材
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 时间倒序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> page = new Page(dto.getPage(), dto.getSize());
        IPage<WmMaterial> result = this.page(page, queryWrapper);
        List<WmMaterial> records = result.getRecords();
        for (WmMaterial record : records) {
            String url = record.getUrl();
            record.setUrl(webSite + url);
        }

        // 3 封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(
                dto.getPage(), dto.getSize(), result.getTotal(), records);
        return pageResponseResult;
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1.参数校验
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        // 2.根据素材id查询素材
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 查看素材是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //如果素材没有被引用,就删除该素材
        removeById(id);
        //同时删除oss文件
        String url = wmMaterial.getUrl();
        log.info("{阿里云 oss文件地址,url}", url);
        System.out.println(url);
        fileStorageService.delete(url);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 1.参数校验
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        //2.更新状态
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if (!wmMaterial.getUserId().equals(uid)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "只允许收藏自己上传的素材");
        }
        wmMaterial.setIsCollection(type);
        updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    /**
     * 检查路径是否是图片的格式
     *
     * @param path
     * @return
     */
    private Boolean checkFileSuffix(String path) {
        if (StringUtils.isBlank(path)) {
            return false;
        }
        List<String> allowSuffix = Arrays.asList("gif", "png", "jpg", "jpeg");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if (path.endsWith(suffix)) {
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }
}
